#include <unistd.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <directory.h>
#include <trim.h>

int procRequest(char *reqeust, char *response, int len);

static char *home;

int
main(int argc, char *argv[])
{
    home = getenv("HOME");
    int listenfd, connfd;
    pid_t childpid;
    struct sockaddr_in servaddr, cliaddr;
    int clilen, n;
    char buff[4096];
    char response[4096];

    listenfd = socket(AF_INET, SOCK_STREAM, 0);

    bzero((char *)&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(1227);

    if (bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) {
        printf("Socket could not be bound, %d\n", errno);
    }

    listen(listenfd, 1024);

    for ( ; ; ) {
        connfd = accept(listenfd, (struct sockaddr *)&cliaddr, &clilen);

        if ((childpid = fork()) == 0) { /* child process */
            close(listenfd);
            while ((n = read(connfd, buff, 4096)) > 0) {
                buff[n] = 0;
                procRequest(buff, response, 4096);
                if (write(connfd, response, strlen(response)) < 0) {
                    printf("write error");
                }
            }
            exit(0);
        }
        if (close(connfd) < 0) {
            printf("close error");
        }
    }
    return 0;
}

int 
procRequest(char *request, char *response, int len)
{
    char cmd[128];
    char *copy = strndup(request, strlen(request));
    char *tokens[2];
    char *tok;
    int  i = 0, rc = 0;
    FILE *fp;

    ltrim(copy, '\n');
    rtrim(copy, '\n');
    tok = strtok(copy, ",");
    while (tok != NULL) {
        tokens[i++] = tok;
        tok = strtok(NULL, ",");
    }

    snprintf(cmd, sizeof(cmd), "python ./urlfetch.py %s %s", tokens[0], tokens[1]);
    system(cmd);

    char csv_file[64];
    snprintf(csv_file, sizeof(csv_file),
        "%s/%s/%s_%s.csv", home, csv_dir, tokens[0], tokens[1]);

    fp = fopen(csv_file, "r");
    if (fp == NULL) {
        /* Create a child process here*/
    } else {
        fgets(response, len, fp);
    }

    return rc;
}
